package com.endurance.service;

import com.endurance.handler.GatewayHandler;
import com.endurance.mapper.GatewayMapper;
import com.endurance.pojo.GatewayHandlerEntity;
import com.endurance.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: sunlin
 * @Date: 2024-05-05 10:57
 * @Version: 1.0
 * @Description:
 */
@Service
@Slf4j
public class HandlerService {

    @Autowired
    private GatewayMapper gatewayMapper;

    private GatewayHandler firstGatewayHandler;

    public GatewayHandler getDbFirstGatewayHandler() {
        if (firstGatewayHandler != null) {
            log.info("已加载firstgatewayhandler");
            return firstGatewayHandler;
        }

        // 1. 从数据中获取查询到得分第一个GatewayHandler
        GatewayHandlerEntity firstGatewayEntity = gatewayMapper.getFirstGatewayHandler();
        if (firstGatewayEntity == null) {
            return null;
        }
        // 2. 从spring中获取该对象
        String firstBeanId = firstGatewayEntity.getHandlerId();
        if (StringUtils.isEmpty(firstBeanId)) {
            return null;
        }
        firstGatewayHandler = SpringUtils.getBean(firstBeanId, GatewayHandler.class);
        if (firstGatewayHandler == null) {
            return null;
        }
        // 3. 使用while循环 递归实现下一个节点的关联
        String nextBeanHandlerId = firstGatewayEntity.getNextHandlerId();
        // 用临时变量保存当前指向的handler
        GatewayHandler tempNextGatewayHandler = firstGatewayHandler;
        while (!StringUtils.isEmpty(nextBeanHandlerId)) {

            // 4. 从spring容器中获取下一个handler对象
            GatewayHandler nextGateWayHandler = SpringUtils.getBean(nextBeanHandlerId, GatewayHandler.class);
            if (nextGateWayHandler == null) {
                break;
            }
            // 5. 通过数据库查询到下一个handler对象信息
            GatewayHandlerEntity nextGatewayhandlerEntity = gatewayMapper.getByHandler(nextBeanHandlerId);
            if (nextGatewayhandlerEntity == null) {
                break;
            }

            nextBeanHandlerId = nextGatewayhandlerEntity.getNextHandlerId();
            // 6. 关联下一个Handler对象
            tempNextGatewayHandler.setNextGatewayhandler(nextGateWayHandler);
            tempNextGatewayHandler = nextGateWayHandler;
        }
        this.firstGatewayHandler = firstGatewayHandler;
        return firstGatewayHandler;
    }

}
